package com.example.gulimall.authserver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.example.common.constant.AuthServerConstant;
import com.example.common.utils.HttpUtils;
import com.example.common.utils.R;
import com.example.gulimall.authserver.feign.MemberFeignService;
import com.example.common.vo.MemberResponseVo;
import com.example.gulimall.authserver.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;


@Controller
@RequestMapping("/oauth2.0")
public class OAuth2Controller {

    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping("/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        Map<String, String> header = new HashMap<>();
        Map<String, String> query = new HashMap<>();
        Map<String,String> map = new HashMap<>();
        map.put("client_id", "4027560673");
        map.put("client_secret", "2fb09490b54ad5e007fd3534dcd15752");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code", code);

        // 1.根据Code 换取accessToken
        HttpResponse post = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", header, query, map);

        // 2.请求成功处理数据
        if(post.getStatusLine().getStatusCode() == 200){
            String string = EntityUtils.toString(post.getEntity());
            SocialUser user = JSON.parseObject(string, SocialUser.class);

            // 检测是否是第一次登录
            R r = memberFeignService.oauth2login(user);
            if(r.getCode() == 0){
                MemberResponseVo data = r.getData(new TypeReference<MemberResponseVo>() {});
                // 第一次使用session 命令浏览器保存这个用户信息 JESSIONSEID 每次只要访问这个网站就会带上这个cookie
                // 在发卡的时候扩大session作用域 (指定域名为父域名)
                // 解决方案：统一存储 和 Hash一致性
                // TODO 1.默认发的当前域的session (需要解决子域session共享问题)
                // TODO 2.使用JSON的方式序列化到redis
                //				new Cookie("JSESSIONID","").setDomain("gulimall.com");
                System.out.println(data.toString());
                session.setAttribute(AuthServerConstant.LOGIN_USER, data);
                // 成功就跳转到首页
                return "redirect:http://gulimall.com";
            }
            return "redirect:http://auth.gulimall.com/login.html";
        }
        return "redirect:http://auth.gulimall.com/login.html";
    }
}
